package com.linln.agent;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.linln.modules.system.domain.Area;
import com.linln.modules.system.service.AreaService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.linln.common.constant.AdminConst;
import com.linln.common.constant.StatusConst;
import com.linln.common.data.URL;
import com.linln.common.enums.ResultEnum;
import com.linln.common.exception.ResultException;
import com.linln.common.utils.MD5;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.help.domain.HelpInfo;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;

/**
 * @author 小懒虫
 * @date 2018/8/14
 */
@Controller
public class AgentLoginController implements ErrorController {

    @Autowired
    private MemberInfoService memberInfoService;
    @Autowired
    private MemberAgentService agentService;

    @Autowired
    private AreaService areaService;

    /**
     * 跳转到登录页面
     */
    @GetMapping("/agent/login")
    public String toLogin(Model model) {
        return "/agent/login";
    }

    /**
     * 实现登录
     */
    @PostMapping("/agent/login")
    @ResponseBody
    public ResultVo login(String username, String password,HttpServletRequest request) {
        // 判断账号密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new ResultException(ResultEnum.USER_NAME_PWD_NULL);
        }

         // 3.执行登录，进入自定义Realm类中
        try {
        	
        	 ExampleMatcher matcher = ExampleMatcher.matching();
             //.withMatcher("type_name", match -> match.contains())
        	 MemberInfo memberInfo=new MemberInfo();
        	 memberInfo.setIsagent(1);
        	 memberInfo.setMobile(username);
		     // 获取数据列表
		     Example<MemberInfo> example = Example.of(memberInfo, matcher);
		     //Sort sort = new Sort(Sort.Direction.ASC, "id");
		     Page<MemberInfo> list = memberInfoService.getPageList(example);
		     if(list!=null && list.getContent()!=null && list.getContent().size()>0) {
	        	 MemberInfo info=list.getContent().get(0);
		    	 HttpSession session=request.getSession();
		            session.setAttribute(AdminConst.AGENT_ROLE_NAME, info); 
		            String md5password=MD5.getMD5String(password);
		            if (info.getPassword().equals(md5password)) {
		                return ResultVoUtil.success("登录成功", new URL("/agent/choicearea"));
		            } else {
		                return ResultVoUtil.error("账户密码不正确");
		            }
		     }else {
	                return ResultVoUtil.error("您不是代理商！");
 
		     }
		    
           
            
        } catch (LockedAccountException e) {
            return ResultVoUtil.error("该账号已被冻结");
        } catch (AuthenticationException e) {
            return ResultVoUtil.error("用户名或密码错误");
        }
    }

    
    
    /**
     * 跳转到登录页面
     */
    @GetMapping("/agent/choicearea")
    public String choicearea(Model model,HttpServletRequest request) {
    	MemberInfo info =(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
    	
    	MemberAgent memberagentarea=new MemberAgent();
    	MemberInfo member=new MemberInfo();
    	member.setId(info.getId());
    	memberagentarea.setMember(member);
    	memberagentarea.setStatus(StatusConst.OK);
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<MemberAgent> example = Example.of(memberagentarea, matcher);
        List<MemberAgent>arealist=agentService.getList(example);
        for (MemberAgent memberAgent :arealist
                ) {
            if(memberAgent==null) continue;
            Area area = areaService.findByCode(memberAgent.getArea());
            if(area != null){
                Area parea = areaService.getById(area.getPid());
                memberAgent.setAreaname(area.getName());
                if(parea != null){
                    memberAgent.setAreaname(parea.getName()+area.getName());
                }
            }
        }
        model.addAttribute("arealist", arealist);
        return "/agent/choicearea";
    }
    
    /**
     * 退出登录
     */
    @GetMapping("/agent/logout")
    public String logout(HttpServletRequest request) {
    	request.getSession().removeAttribute(AdminConst.AGENT_ROLE_NAME);
        SecurityUtils.getSubject().logout();
        return "redirect:/agent/login";
    }

    /**
     * 权限不足页面
     */
    @GetMapping("/agent/noAuth")
    public String noAuth() {
        return "/agent/main/noAuth";
    }

    /**
     * 自定义错误页面
     */
    @Override
    public String getErrorPath() {
        return "/error";
    }

    /**
     * 处理错误页面
     */
    @RequestMapping("/agent/error")
    public String handleError(Model model, HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String errorMsg = "好像出错了呢！";
        if (statusCode == 404) {
            errorMsg = "页面找不到了！好像是去火星了~";
        }

        model.addAttribute("statusCode", statusCode);
        model.addAttribute("msg", errorMsg);
        return "/agent/main/error";
    }
}
